package com.cauli.account.config.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.convert.ConvertException;
import cn.hutool.core.util.EnumUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cauli.account.config.mapper.ConfigMapper;
import com.cauli.account.config.model.dto.ConfigDetailDTO;
import com.cauli.account.config.model.dto.ConfigQueryDTO;
import com.cauli.account.config.model.entity.Config;
import com.cauli.account.config.service.ConfigService;
import com.cauli.utils.util.EnumConvertUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Cauli
 * @date 2022-12-14 17:01:10
 * @description 系统设置表 服务实现类
 */
@Slf4j
@Service
public class ConfigServiceImpl extends ServiceImpl<ConfigMapper, Config> implements ConfigService {
    public ConfigDetailDTO getConfig(ConfigQueryDTO configQueryDTO) {
        ConfigDetailDTO configDetailDTO = new ConfigDetailDTO();
        List<Config> configList = new ArrayList<>();
        if (configQueryDTO != null) {
            LambdaQueryWrapper<Config> configLambdaQueryWrapper = configQueryDTO.toLambdaQueryWrapper();
            configList = baseMapper.selectList(configLambdaQueryWrapper);
        } else {
            configList = baseMapper.findAll();
        }

        for (Config config : configList) {
            String key = config.getConfigName();
            try {
                Field field = ConfigDetailDTO.class.getDeclaredField(key);
                field.setAccessible(true);
                Class<?> fieldType = field.getType();
                String configValue = config.getConfigValue();

                Object convertVal;
                if (EnumUtil.isEnum(fieldType)) {
                    convertVal = EnumConvertUtils.convertStrToEnum(fieldType, configValue);
                } else {
                    convertVal = Convert.convert(fieldType, configValue);
                }
                field.set(configDetailDTO, convertVal);
            } catch (NoSuchFieldException | IllegalAccessException | ConvertException e) {
                log.error("通过反射, 将字段 {} 注入configDTO时出现异常：", key, e);
            }
        }
        return configDetailDTO;
    }
}




